package results

import (
	"fmt"
	goerrors "github.com/go-errors/errors"
)

var ErrMap map[string]map[int]string

type CustomError struct {
	errCode int            `json:"errCode"`
	Msg     string         `json:"msg"`
	Data    interface{}    `json:"data"`
	err     goerrors.Error `json:"err"`
}

func (err *CustomError) Error() string {
	return err.err.Error()
}

func (err *CustomError) ErrorStack() string {
	return err.err.ErrorStack()
}

func NewError(errCode int, locale string, e interface{}) *CustomError {
	goerrors.MaxStackDepth = 5
	return &CustomError{
		errCode: errCode,
		Msg:     ErrMap[locale][errCode],
		err:     *goerrors.New(e),
	}
}

func New(data interface{}) *CustomError {
	return &CustomError{Msg: "success", Data: data}
}

func Wrap(e interface{}) *CustomError {
	var err error

	switch e := e.(type) {
	case *CustomError:
		return e
	case error:
		err = e
	default:
		err = fmt.Errorf("%v", e)
	}

	return &CustomError{
		Msg: "unknown err",
		err: *goerrors.New(err),
	}
}
